// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const subMchId = "1636715260"
const envId = "wjs-4gpwpq5j4372152f"

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const {
    nonce_str,
    out_trade_no,
    total_fee,
    refund_fee,
    title
  } = event
  const res = await cloud.cloudPay.refund({
    envId,
    functionName: 'refoundCallback', // 可以是一个空的云函数
    sub_mch_id: subMchId, // 在云开发控制台中查看
    nonce_str,
    out_trade_no,
    out_refund_no: createOutTradeNo(),
    total_fee,
    refund_fee,
  })
  return res
}

const createOutTradeNo = () => {
  let outTradeNo = new Date().getTime() // 获取当前13位时间戳
  let numStr = '0123456789';
  let randomStr = '';
  for (let i = (32 - 13); i > 0; --i) {
    randomStr += numStr[Math.floor(Math.random() * numStr.length)];
  }
  outTradeNo += randomStr
  return outTradeNo
}